#!/bin/bash

# Parameters
remote_image_repo="${REMOTE_IMAGE_REPO:-rruijfang/oj-}"
compose_file="${COMPOSE_FILE:-docker-compose.yaml}"

# Function to rebuild Docker compose for all services
rebuild_all() {
    echo "Rebuilding all Docker services..."
    docker compose -f "$compose_file" build || { echo "Failed to build Docker services."; exit 1; }
    docker-compose -f "$compose_file" up -d || { echo "Failed to start Docker services."; exit 1; }
}

# Function to rebuild Docker compose for a specific service
rebuild_service() {
    service_name="$1"
    echo "Rebuilding Docker service: $service_name"
    docker compose -f "$compose_file" build "$service_name" || { echo "Failed to build Docker service: $service_name."; exit 1; }
    docker compose -f "$compose_file" up -d "$service_name" || { echo "Failed to start Docker service: $service_name."; exit 1; }
}

# Function to tag and push Docker service
tag_and_push_service() {
    service_name="$1"
    version="$2"
    echo "Tagging Docker service: $service_name"
    docker tag "$service_name:local" "$remote_image_repo$service_name:$version" || { echo "Failed to tag Docker service: $service_name."; exit 1; }
    docker tag "$remote_image_repo$service_name:$version" "$remote_image_repo$service_name:latest" || { echo "Failed to tag Docker service: $service_name."; exit 1; }
    echo "Pushing Docker service: $remote_image_repo$service_name:$version"
    docker push "$remote_image_repo$service_name:latest" || { echo "Failed to push Docker service: $service_name."; exit 1; }
}

initialize_swag() {
    echo "Initializing swag..."
    ./web/swag init -g ./web/service/ahutoj/ahutoj.go -o ./web/docs || { echo "Failed to initialize swag."; exit 1; }
}

# Main script logic
case "$1" in
    all)
        rebuild_all
        ;;
    origin | oj | gateway | forum | judged)
        rebuild_service "$1"
        ;;
    swag)
        initialize_swag
        ;;
    tp)
        if [ -n "$2" ] && [ -n "$3" ] && [[ "$2" =~ ^(origin|oj|gateway|forum|judged)$ ]]; then
            tag_and_push_service "$2" "$3"
        else
            echo "Usage: $0 tp <origin|oj|gateway|forum|judged> <version>"
            exit 1
        fi
        ;;
    *)
        echo "Usage: $0 <all|origin|oj|gateway|forum|judged|swag|tp>"
        exit 1
        ;;
esac

exit 0
